package nl.infodation.emr.pricingservice.ui;

import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.regex.Pattern;

import net.atontech.vaadin.ui.numericfield.NumericField;
import nl.infodation.emr.pricingservice.business.BusinessFactory;
import nl.infodation.emr.pricingservice.controller.ControllerFactory;
import nl.infodation.emr.pricingservice.controller.IController;
import nl.infodation.emr.pricingservice.data.AppliesSelection;
import nl.infodation.emr.pricingservice.data.ConditionItem;
import nl.infodation.emr.pricingservice.data.ListBoxData;
import nl.infodation.emr.pricingservice.data.PromotionConnectedSelection;
import nl.infodation.emr.pricingservice.entity.DomainRule;
import nl.infodation.emr.pricingservice.entity.DomainRule.CustomerVip;
import nl.infodation.emr.pricingservice.entity.DomainRule.PriceType;
import nl.infodation.emr.pricingservice.entity.Environment;
import nl.infodation.emr.pricingservice.entity.Role;
import nl.infodation.emr.pricingservice.entity.SystemDetail;
import nl.infodation.emr.pricingservice.entity.SystemValue.TableName;
import nl.infodation.emr.pricingservice.entity.SystemValueRef;
import nl.infodation.emr.pricingservice.ui.component.IView;
import nl.infodation.emr.pricingservice.ui.page.SessionData;
import nl.infodation.emr.utility.BooleanUtil;
import nl.infodation.emr.utility.Constants;
import nl.infodation.emr.utility.CreateElementOnGui;
import nl.infodation.emr.utility.CreateElementOnGui.StyleNameCss;
import nl.infodation.emr.utility.DateTimeUtil;
import nl.infodation.emr.utility.DefaultObjectFactory;
import nl.infodation.emr.utility.ListenerUtil;
import nl.infodation.emr.utility.StringUtil;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.BeanItem;
import com.vaadin.terminal.UserError;
import com.vaadin.ui.AbstractField;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.CustomLayout;
import com.vaadin.ui.Field;
import com.vaadin.ui.Label;
import com.vaadin.ui.ListSelect;
import com.vaadin.ui.PopupDateField;
import com.vaadin.ui.Select;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.Notification;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class ConditionView extends CustomComponent implements IView,
		ClickListener, ValueChangeListener {
	private static final Logger LOG = LoggerFactory
			.getLogger(ConditionView.class);

	private static final int PROMOTION_CODE_LIMIT = 5;
	private static final String ENVIRONMENT = " Environment";
	private static final long serialVersionUID = -2340142428763112076L;
	private static final String COUNTRY_CODE = "RU";

	private CustomLayout conditionCustomLayout;
	private Label lblGeneralConditions;
	private Label lblAccessManagement;
	private Label lblPromotionConnectedTo;
	private Label lblOrdersConditions;
	private Label lblAppliesTo;
	private Label lblRuleAttributes;
	private NumericField tfSalience;
	private TextArea taDescription;
	private TextField tfRuleName;
	private CheckBox chbProductId;
	private TextField tfProductId;
	private Button btnSelectApplies;
	private TextField tfProductCode;
	private TextField tfBrand;
	private NumericField tfOfferId;
	private NumericField tfLots;
	private CheckBox chbCategory;
	private TextField tfCategory;
	private TextField tfSubFamily;
	private CheckBox chbBundleDefinition;
	private TextField tfOneProduceForEachSubFamily;
	private TextField tfBundleDefinition;
	private CheckBox chbOneProduceForEachSubFamily;
	private CheckBox chbOfferId;
	private CheckBox chbBrand;
	private CheckBox chbLots;
	private CheckBox chbProductCode;
	private CheckBox chbSubFamilly;
	private CheckBox chbFamilyCode;
	private CheckBox chbDeliveryModePriceRange;
	private Label lblBusiness;
	private Label lblEnvironmentName;
	private TextField tfMarketingActionCode;
	private Button btnCancel;
	private Button btnSave;
	private TextField tfMoreThanXFamilyValue;
	private CheckBox chbMoreThanXFamilyEnable;
	private NumericField tfNbOfItemPerOrderCond;
	private NumericField tfLineAmountCond;
	private NumericField tfOrderAmountCond;
	private NumericField tfNetAmountCond;
	private Button btnSelectPromotionConnected;
	private NumericField tfSalesId;
	//private TextField tfCityType;
	private Select cbbShippingMode;
	private TextField tfPromotionItemCode;
	private CheckBox chbCityType;
	private CheckBox chbSalesId;
	private CheckBox chbShippingMode;
	private CheckBox chbPromotionCode;
	private ComboBox cbbBusLine;
	private ComboBox cbbCityCode;
	private PopupDateField tfEndDate;
	private PopupDateField tfBeginDate;
	private Select cbbCountry;
	private Select cbbLanguage;
	private Select cbbChannel;
	private Select cbbPaymentMode;
	private Select cbbDeliveryMode;
	private Select cbbOffer;
	private Select cbbFamilyCode;
	private Select cbbSubFamilyCode;
	private Select cbbCategory;
	private Select cbbCurrency;
	private TextField tfDeliveryModePriceRange;
	private CheckBox chbChannelEnable;
	private CheckBox chbPaymentModeEnable;
	private ComboBox cbbCustomerVip;
	private ComboBox cbbPriceType;
	
	private Select cbbLocation;
	private TextField tfAccessProductId;
	private PopupDateField tfAccessDatetime;
	private Select cbbAccessType;
	
	private Long promotionId;
	private Environment environment;
	public ConditionItem curConditionItem;
	private MainView parentView;
	private boolean chbPromotionCodeIsCheck;
	private boolean chbXofFamilyCheck;

	private String oldName;
	private boolean isUpdate = false;

	private PromotionCodePopup promotionCodePopup;

	public ConditionView(MainView parentView) {
		this.parentView = parentView;
		initLayout();
	}

	public ConditionView() {
	}

	public boolean getChbXofFamilyCheck() {
		return chbXofFamilyCheck;
	}

	public void setChbXofFamilyCheck(boolean chbXofFamilyCheck) {
		this.chbXofFamilyCheck = chbXofFamilyCheck;
	}

	public boolean getchbPromotionCodeIsCheck() {
		return chbPromotionCodeIsCheck;
	}

	public void setchbPromotionCodeIsCheck(boolean chbPromotionCodeIsCheck) {
		this.chbPromotionCodeIsCheck = chbPromotionCodeIsCheck;
	}

	@Override
	public void initLayout() {
		buildMainLayout();
		setFormatDateField();
		setCaptionForMultiLanguage();
		addConstrains();
		this.setCompositionRoot(conditionCustomLayout);
		addListener();
		initEnvironmentHeader();
		setOptionForBusLine();		
	}

	private void setFormatDateField() {
		tfBeginDate.setDateFormat(Constants.DATE_FORMAT_STRING);
		tfEndDate.setDateFormat(Constants.DATE_FORMAT_STRING);
	}

	private void setOptionForBusLine() {
		cbbBusLine.setNullSelectionAllowed(false);
		cbbBusLine.removeAllItems();
		if (SessionData.isSuperAdmin()) {
			final List<Role> roles = BusinessFactory.getSystemBusiness().findAllRoles();

			boolean isFirstItem = Boolean.TRUE;
			for (Role role : roles) {
				cbbBusLine.addItem(role.getRoleName());
				// init first Role for dropdownbox ActionListenner
				if (isFirstItem) {
					initRoleForCombobox();
					isFirstItem = !isFirstItem;
				}
			}
		} else {
			final String roleName = SessionData.getRoleName();
			cbbBusLine.addItem(roleName);
			initRoleForCombobox();
		}

	}

	private void initRoleForCombobox() {
		final Role searchItem = new Role();
		searchItem.setRoleName((String) cbbBusLine.getValue());
	}

	public String getCountryCode() {
		String country = null;
		if (cbbCountry.getValue() != null) {
			country = (String) cbbCountry.getValue();
		}
		return country;
	}

	public String getBussinessLine() {
		String bussiness = null;
		if (cbbBusLine.getValue() != null) {
			bussiness = (String) cbbBusLine.getValue();
		}
		return bussiness;
	}

	public void setCountryCode(final String value) {
		cbbCountry.setValue(value);
	}

	public String getLanguageCode() {
		String language = null;
		if (cbbLanguage.getValue() == null) {

		} else {
			language = (String) cbbLanguage.getValue();
		}
		return language;
	}

	public String getPriceType() {
		String priceType = "";
		if (cbbPriceType.getValue() != null) {
			priceType = ((PriceType) cbbPriceType.getValue()).value();
		}
		return priceType;
	}

	private void initEnvironmentHeader() {
		final Environment env = BusinessFactory.getSystemBusiness()
				.getEnvironment(SessionData.getEnvironment());
		if (env != null) {
			final String envName = env.getEnvironmentName() + ENVIRONMENT;
			lblEnvironmentName.setValue(envName);
		}
	}

	public void setBinding(final Property busProperty,
			final Property ruleProperty, final Property envProperty) {
		cbbBusLine.setPropertyDataSource(busProperty);
		tfRuleName.setPropertyDataSource(ruleProperty);
		lblEnvironmentName.setPropertyDataSource(envProperty);
	}

	private void addConstrains() {
		cbbBusLine.setRequired(true);
		cbbCountry.setRequired(true);
		tfBeginDate.setRequired(true);
		tfRuleName.setRequired(true);
		taDescription.setRequired(true);
		tfPromotionItemCode.setRequired(true);
		tfMoreThanXFamilyValue.setRequired(true);
		tfSalesId.setRequired(Boolean.TRUE);
		tfLots.setRequired(Boolean.TRUE);
		tfOfferId.setRequired(Boolean.TRUE);
	}

	public boolean validateName(final String ruleName) {
		return Boolean.TRUE;
	}

	public boolean validate() {
		Date beginDate = (Date) tfBeginDate.getValue();
		Date endDate = (Date) tfEndDate.getValue();
		String ruleName = (String) tfRuleName.getValue();

		int isRuleExist = BusinessFactory.getRuleBusiness().existRuleName(ruleName);
		removeError();
		String xofFamily = (String) tfMoreThanXFamilyValue.getValue();
		if ((boolean) chbMoreThanXFamilyEnable.getValue()) {
			if (StringUtil.isEmptyOrBlank(xofFamily)
					|| regularIntegerExpressCheck(xofFamily) == false) {
				setComponentError(tfMoreThanXFamilyValue, SessionData.getI18N()
						.getMessage(Constants.XOFFAMILYREQUIRED));
				return Boolean.FALSE;
			}
		}

		if ((boolean) chbLots.getValue()) {
			String lotValue = (String) tfLots.getValue();
			if (!StringUtil.isEmptyOrBlank(lotValue)) {
				if (regularIntegerExpressCheck(lotValue) == false) {
					setComponentError(
							tfLots,
							SessionData.getI18N().getMessage(
									Constants.LOT_VALUE));
					return Boolean.FALSE;
				}
			}
		}

		if ((boolean) chbOfferId.getValue()) {
			String offerValue = (String) tfOfferId.getValue();
			if (!StringUtil.isEmptyOrBlank(offerValue)) {
				if (regularIntegerExpressCheck(offerValue) == false) {
					setComponentError(tfOfferId, SessionData.getI18N()
							.getMessage(Constants.OFFERID_VALUE));
					return Boolean.FALSE;
				}
			}
		}

		if ((boolean) chbSalesId.getValue()) {
			String saleValue = (String) tfSalesId.getValue();
			if (!StringUtil.isEmptyOrBlank(saleValue)) {
				if (regularIntegerExpressCheck(saleValue) == false) {
					setComponentError(tfSalesId, SessionData.getI18N()
							.getMessage(Constants.SALEID_VALUE));
					return Boolean.FALSE;
				}
			}
		}

		String saleValue = (String) tfNbOfItemPerOrderCond.getValue();
		if (!StringUtil.isEmptyOrBlank(saleValue)) {
			if (regularIntegerExpressCheck(saleValue) == false) {
				setComponentError(tfNbOfItemPerOrderCond, SessionData.getI18N()
						.getMessage(Constants.SALEID_VALUE));
				return Boolean.FALSE;
			}
		}

		if ((boolean) chbPromotionCode.getValue()) {
			String promotionCode = (String) tfPromotionItemCode.getValue();
			boolean invalid = isNotStringGroup(promotionCode);
			if (StringUtil.isEmptyOrBlank((String) tfPromotionItemCode
					.getValue())
					|| invalid == Boolean.TRUE
					|| regularExpressCheck(promotionCode) == false) {
				setComponentError(tfPromotionItemCode, SessionData.getI18N()
						.getMessage(Constants.PROMOTION_CODE_REQUIRED_MESSAGE));
				return Boolean.FALSE;
			} else {
				String promtionCode = tfPromotionItemCode.getValue().toString();
				if (promtionCode.length() > PROMOTION_CODE_LIMIT) {
					setComponentError(
							tfPromotionItemCode,
							SessionData.getI18N().getMessage(
									Constants.PROMOTION_CODE_LENGTH_MESSAGE));
					return Boolean.FALSE;
				}
			}
		}

		if (StringUtil.isEmptyOrBlank((String) cbbBusLine.getValue())) {
			setComponentError(
					cbbBusLine,
					SessionData.getI18N().getMessage(
							Constants.BUSINESS_LINE_REQUIRED));
			return Boolean.FALSE;

		} else if (isNullOrEmpty(taDescription.getValue())) {
			setComponentError(
					taDescription,
					SessionData.getI18N().getMessage(
							Constants.DESCRIPTION_REQUIRED_MESSAGE));
			return Boolean.FALSE;

		} else if (isNullOrEmpty(cbbCountry.getValue())) {
			setComponentError(
					cbbCountry,
					SessionData.getI18N().getMessage(
							Constants.COUNTRY_REQUIRED_MESSAGE));
			return Boolean.FALSE;

		} else if (beginDate == null) {
			setComponentError(
					tfBeginDate,
					SessionData.getI18N().getMessage(
							Constants.BEGIN_DATE_REQUIRED_MESSAGE));
			return Boolean.FALSE;

		} else if (ruleName.contains("\"")) {

			setComponentError(
					tfRuleName,
					SessionData.getI18N().getMessage(
							Constants.RULE_NAME_REQUIRED_MESSAGE));
			return Boolean.FALSE;

		} else if (endDate != null && beginDate.compareTo(endDate) > 0) {

			setComponentError(
					tfEndDate,
					SessionData.getI18N().getMessage(
							Constants.BEGIN_DATE_REQUIRED_MESSAGE));
			return Boolean.FALSE;
		}

		else if (StringUtil.isEmptyOrBlank(ruleName)) {
			setComponentError(
					tfRuleName,
					SessionData.getI18N().getMessage(
							Constants.RULE_NAME_REQUIRED_MESSAGE));
			return Boolean.FALSE;

		} else if (isRuleExist > 0 && !isUpdate) {
			setComponentError(
					tfRuleName,
					SessionData.getI18N().getMessage(
							Constants.RULE_NAME_REQUIRED_MESSAGE));
			return Boolean.FALSE;
		} else if (isUpdate && !ruleName.equalsIgnoreCase(oldName)) {
			if (isRuleExist > 0) {
				setComponentError(
						tfRuleName,
						SessionData.getI18N().getMessage(
								Constants.RULE_NAME_REQUIRED_MESSAGE));
				return Boolean.FALSE;
			}
		} else if (String.valueOf(taDescription.getValue()).contains("\"")) {

			setComponentError(
					taDescription,
					SessionData.getI18N().getMessage(
							Constants.DESCRIPTION_REQUIRED_MESSAGE));
			return Boolean.FALSE;

		}

		removeError();
		return true;
	}

	private boolean isNotStringGroup(final String str) {
		boolean invalid = Boolean.FALSE;
		for (int i = 0; i < str.length(); i++) {
			if (String.valueOf(str.charAt(0)).equals(";")
					|| String.valueOf(
							str.charAt(str.length() - 1))
							.equals(";")) {
				invalid = true;
				break;
			}
			if (i < (str.length() - 1)) {
				if (String.valueOf(str.charAt(i)).equals(";")
						&& String.valueOf(str.charAt(i + 1))
								.endsWith(";")) {
					invalid = true;
					break;
				}
			}
		}
		return invalid;
	}

	private boolean regularExpressCheck(final String value) {
		String speCharacter = "[^\\^()<>,:?/~\\*%$\"]*";
		return Pattern.matches(speCharacter, value);
	}

	private boolean regularIntegerExpressCheck(final String value) {
		return Pattern.matches("[0-9]{1,9}", value);
	}

	private void removeError() {
		cbbBusLine.setComponentError(null);
		tfEndDate.setComponentError(null);
		cbbCountry.setComponentError(null);
		tfBeginDate.setComponentError(null);
		tfRuleName.setComponentError(null);
		taDescription.setComponentError(null);
		tfPromotionItemCode.setComponentError(null);
		tfMoreThanXFamilyValue.setComponentError(null);
		tfSalesId.setComponentError(null);
		tfLots.setComponentError(null);
		tfOfferId.setComponentError(null);
	}

	private void setComponentError(final AbstractField component,
			final String msgError) {
		component.focus();
		component.setComponentError(new UserError(msgError));
	}

	private void setCaptionForMultiLanguage() {

		lblGeneralConditions.setValue(SessionData.getI18N().getMessage(
				Constants.GENERAL_CONDITIONS_PANEL));
		lblAccessManagement.setValue(SessionData.getI18N().getMessage(
						Constants.ACCESS_MANAGEMENT_PANEL));
		lblPromotionConnectedTo.setValue(SessionData.getI18N().getMessage(
				Constants.PROMOTION_CONNECTED_TO_PANEL));
		lblOrdersConditions.setValue(SessionData.getI18N().getMessage(
				Constants.ORDERS_CONDITIONS_PANEL));
		lblAppliesTo.setValue(SessionData.getI18N().getMessage(
				Constants.APPLIES_TO_PANEL));
		lblRuleAttributes.setValue(SessionData.getI18N().getMessage(
				Constants.RULE_ATTRIBUTES_PANEL));
		cbbBusLine.setCaption(SessionData.getI18N().getMessage(
				Constants.BUS_LINE_TEXTFIELD));
		cbbCountry.setCaption(SessionData.getI18N().getMessage(
				Constants.COUNTRY_TEXTFIELD));
		cbbLanguage.setCaption(SessionData.getI18N().getMessage(
				Constants.LANGUAGE_TEXTFIELD));
		chbChannelEnable.setCaption(SessionData.getI18N().getMessage(
				Constants.CHANNEL_HEADER));
		chbPaymentModeEnable.setCaption(SessionData.getI18N().getMessage(
				Constants.PAYMENT_MODE_CHECKBOX));
		cbbDeliveryMode.setCaption(SessionData.getI18N().getMessage(
				Constants.DELIVERY_MODE));
		cbbOffer.setCaption(SessionData.getI18N().getMessage(Constants.OFFER));
		chbFamilyCode.setCaption(SessionData.getI18N().getMessage(
				Constants.FAMILY_HEADER));
		cbbCurrency.setCaption(SessionData.getI18N().getMessage(
				Constants.CURRENCY_CHECKBOX));
		tfBeginDate.setCaption(SessionData.getI18N().getMessage(
				Constants.BEGIN_DATE_TEXTFIELD));
		tfEndDate.setCaption(SessionData.getI18N().getMessage(
				Constants.END_DATE_TEXTFIELD));
		chbPromotionCode.setCaption(SessionData.getI18N().getMessage(
				Constants.PROMOTION_CODE_CHECKBOX));
		tfSalience.setCaption(SessionData.getI18N().getMessage(
				Constants.SALIENCE));
		chbShippingMode.setCaption(SessionData.getI18N().getMessage(
				Constants.SHIPPING_MODE_CHECKBOX));
		chbSalesId.setCaption(SessionData.getI18N().getMessage(
				Constants.SALES_ID_CHECKBOX));
		chbCityType.setCaption(SessionData.getI18N().getMessage(
				Constants.CITY_TYPE_CHECKBOX));
		tfOrderAmountCond.setCaption(SessionData.getI18N().getMessage(
				Constants.ORDER_AMOUNT_TEXTFIELD));
		tfNetAmountCond.setCaption(SessionData.getI18N().getMessage(
				Constants.NET_AMOUNT_TEXTFIELD));
		tfLineAmountCond.setCaption(SessionData.getI18N().getMessage(
				Constants.LINE_AMOUNT_TEXTFIELD));
		tfNbOfItemPerOrderCond.setCaption(SessionData.getI18N().getMessage(
				Constants.NB_OF_ITEM_PER_ORDER_COND_TEXTFIELD));
		btnSave.setCaption(SessionData.getI18N().getMessage(
				Constants.SAVE_BUTTON));
		tfMarketingActionCode.setCaption(SessionData.getI18N().getMessage(
				Constants.MARKETING_ACTION_CODE_TEXTFIELD));
		chbSubFamilly.setCaption(SessionData.getI18N().getMessage(
				Constants.SUB_FAMILLY_CHECKBOX));
		chbCategory.setCaption(SessionData.getI18N().getMessage(
				Constants.CATEGORY_CHECKBOX));
		chbProductCode.setCaption(SessionData.getI18N().getMessage(
				Constants.PRODUCT_CODE_CHECKBOX));
		chbLots.setCaption(SessionData.getI18N().getMessage(
				Constants.LOTS_CHECKBOX));
		chbBrand.setCaption(SessionData.getI18N().getMessage(
				Constants.BRAND_CHECKBOX));
		chbOfferId.setCaption(SessionData.getI18N().getMessage(
				Constants.OFFER_ID_CHECKBOX));
		chbOneProduceForEachSubFamily
				.setCaption(SessionData.getI18N().getMessage(
						Constants.ONE_PRODUCE_FOR_EACH_SUB_FAMILY_CHECKBOX));
		chbBundleDefinition.setCaption(SessionData.getI18N().getMessage(
				Constants.BUNDLE_DEFINITION_CHECKBOX));
		tfRuleName.setCaption(SessionData.getI18N().getMessage(
				Constants.RULE_NAME_LABEL));
		taDescription.setCaption(SessionData.getI18N().getMessage(
				Constants.DESCRIPTION_LABEL));
		btnSelectApplies.setCaption(SessionData.getI18N().getMessage(
				Constants.SELECT_BUTTON));
		btnSelectPromotionConnected.setCaption(SessionData.getI18N()
				.getMessage(Constants.SELECT_BUTTON));
		lblBusiness.setValue(SessionData.getI18N().getMessage(
				Constants.BUSINESS_LABEL));
		chbMoreThanXFamilyEnable.setCaption(SessionData.getI18N().getMessage(
				Constants.MORE_THAN_X_FAMILY_CHECKBOX));
		chbProductId.setCaption(SessionData.getI18N().getMessage(
				Constants.PRODUCT_ID_CHECKBOX));
		chbDeliveryModePriceRange.setCaption(SessionData.getI18N().getMessage(
				Constants.DELIVERY_MODE_PRICE_RANGE));
		cbbCustomerVip.setCaption(SessionData.getI18N().getMessage(
				Constants.CUSTOMMER_VIP));
		cbbPriceType.setCaption(SessionData.getI18N().getMessage(
				Constants.PRICE_TYPE));
		cbbLocation.setCaption(SessionData.getI18N().getMessage(
				Constants.LOCATION_COMBOBOX));
		cbbAccessType.setCaption(SessionData.getI18N().getMessage(
				Constants.ACCESS_TYPE_COMBOBOX));
		tfAccessDatetime.setCaption(SessionData.getI18N().getMessage(
				Constants.ACCESS_DATETIME_TEXTFIELD));
		tfAccessProductId.setCaption(SessionData.getI18N().getMessage(
				Constants.ACCESS_PRODUCT_ID_TEXTFIELD));
		
		lblCustomerConditions.setCaption(SessionData.getI18N().getMessage(
				Constants.ACCESS_PRODUCT_ID_TEXTFIELD));
		lbxServiceProviderDomainId.setCaption(SessionData.getI18N().getMessage(
				Constants.ACCESS_PRODUCT_ID_TEXTFIELD));
		cbbCustomerRole.setCaption(SessionData.getI18N().getMessage(
				Constants.ACCESS_PRODUCT_ID_TEXTFIELD));
		cbbCustomerStatus.setCaption(SessionData.getI18N().getMessage(
				Constants.ACCESS_PRODUCT_ID_TEXTFIELD));
		cbbCustomerClassification.setCaption(SessionData.getI18N().getMessage(
				Constants.ACCESS_PRODUCT_ID_TEXTFIELD));
		cbbCustomerBalanceOperator.setCaption(SessionData.getI18N().getMessage(
				Constants.ACCESS_PRODUCT_ID_TEXTFIELD));
	}

	private String replace(final String source) {
		if (source == null) {
			return "";
		}
		return source.trim().replace(" ", ";");
	}

	private void addListener() {
		btnSave.addListener((ClickListener) this);
		btnCancel.addListener((ClickListener) this);
		btnSelectApplies.addListener((ClickListener) this);
		btnSelectPromotionConnected.addListener((ClickListener) this);

		ListenerUtil.addValueChangeListenerToComboBox(cbbBusLine,
				new ValueChangeListener() {
					private static final long serialVersionUID = 1L;

					@Override
					public void valueChange(final ValueChangeEvent event) {
						if (!StringUtil.isEmptyOrBlank((String) cbbBusLine
								.getValue())) {
							String value = cbbBusLine.getValue().toString();
							if (value != null) {
								setVisibleToobar(value);
								reloadAllSelectBox(StringUtil
										.getValueWithoutNull((String) cbbBusLine
												.getValue()));
							}
						}
					}
				});

		cbbPriceType.addListener(new ValueChangeListener() {

			private static final long serialVersionUID = 1L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				parentView
						.setOrderLineDiscountStateFromAdvantageView(getPriceType());
			}
		});

		cbbCountry.setImmediate(Boolean.TRUE);
		cbbCountry.addListener(new ValueChangeListener() {
			private static final long serialVersionUID = 237324073573310939L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				String countryCode = (String) event.getProperty().getValue();
				if (countryCode != null && countryCode.equals(COUNTRY_CODE)) {
					cbbCityCode.setVisible(Boolean.TRUE);	
					chbCityType.setVisible(Boolean.TRUE);
					chbCityType.setValue(Boolean.TRUE);
				} else {
					cbbCityCode.setVisible(Boolean.FALSE);				
					cbbCityCode.setValue(null);
					chbCityType.setVisible(Boolean.FALSE);
					chbCityType.setValue(Boolean.FALSE);
				}
			}
		});
		
		
		ListenerUtil.addValueChangeListenerToTextField(tfOneProduceForEachSubFamily, new ValueChangeListener() {
			
			@Override
			public void valueChange(ValueChangeEvent event) {
				Property property = event.getProperty();
				if (null != property && null != property.getValue()) {
					isNotStringGroup((String)property.getValue());
					
					if (isNotStringGroup((String)property.getValue())) {
						setComponentError(
								tfOneProduceForEachSubFamily,
								SessionData
										.getI18N()
										.getMessage(
												Constants.MUST_BE_STRING_GROUP));
					} else {
						tfOneProduceForEachSubFamily.setComponentError(null);
					}
				}
				
			}
		});
		
		ListenerUtil.addValueChangeListenerToComboBox(cbbBusLine,
				new ValueChangeListener() {
					private static final long serialVersionUID = 1L;

					@Override
					public void valueChange(ValueChangeEvent event) {
						Property property = event.getProperty();
						SessionData.setRoleNameForRefData((String) property
								.getValue());
					}
				});

		ListenerUtil.addValueChangeListenerToTextField(tfProductId,
				new ValueChangeListener() {
					private static final long serialVersionUID = 1L;

					@Override
					public void valueChange(ValueChangeEvent event) {
						Property property = event.getProperty();
						SessionData.setRoleNameForRefData((String) property
								.getValue());
					}
				});

		// validate that tfProductId can put many number separated by ';'
		// character.
		ListenerUtil.addValueChangeListenerToTextField(tfProductId,
				new ValueChangeListener() {
					private static final long serialVersionUID = 1L;

					@Override
					public void valueChange(ValueChangeEvent event) {
						Property property = event.getProperty();
						String value = StringUtil
								.getValueWithoutNull((String) property
										.getValue());
						if (!StringUtil.isEmptyOrBlank(value)) {
							if (!isIntegerGroup(value)) {
								setComponentError(
										tfProductId,
										SessionData
												.getI18N()
												.getMessage(
														Constants.MUST_BE_INTEGER_GROUP));
							} else {
								tfProductId.setComponentError(null);
							}
						}
					}

					private boolean isDigit(char ch) {
						return ch >= '0' && ch <= '9';
					}

					private boolean isIntegerGroup(String value) {
						boolean isIntegerGroup = Boolean.TRUE;

						char separatedCharacter = ';';

						if (value.startsWith(String.valueOf(separatedCharacter))) {
							return Boolean.FALSE;
						}

						if (value.endsWith(String.valueOf(separatedCharacter))) {
							return Boolean.FALSE;
						}

						for (char ch : value.toCharArray()) {
							if (!isDigit(ch) && ch != separatedCharacter) {
								return Boolean.FALSE;
							}
						}
						return isIntegerGroup;
					}
				});

		// Copy-paste from excel file
		ListenerUtil.addValueChangeListenerToTextField(tfPromotionItemCode,
				(ValueChangeListener) this);		
		ListenerUtil.addValueChangeListenerToTextField(tfSubFamily,
				(ValueChangeListener) this);

		// set listener
		ListenerUtil.addClickListenerToCheckBox(chbChannelEnable,
				(ClickListener) this);
		ListenerUtil.addClickListenerToCheckBox(chbBundleDefinition,
				(ClickListener) this);
		ListenerUtil.addClickListenerToCheckBox(chbOneProduceForEachSubFamily,
				(ClickListener) this);
		ListenerUtil.addClickListenerToCheckBox(chbOfferId,
				(ClickListener) this);
		ListenerUtil.addClickListenerToCheckBox(chbBrand, (ClickListener) this);
		ListenerUtil.addClickListenerToCheckBox(chbLots, (ClickListener) this);
		ListenerUtil.addClickListenerToCheckBox(chbProductCode,
				(ClickListener) this);
		ListenerUtil.addClickListenerToCheckBox(chbSubFamilly,
				(ClickListener) this);
		ListenerUtil.addClickListenerToCheckBox(chbCategory,
				(ClickListener) this);
		ListenerUtil.addClickListenerToCheckBox(chbCityType,
				(ClickListener) this);
		ListenerUtil.addClickListenerToCheckBox(chbSalesId,
				(ClickListener) this);
		ListenerUtil.addClickListenerToCheckBox(chbShippingMode,
				(ClickListener) this);
		ListenerUtil.addClickListenerToCheckBox(chbPromotionCode,
				(ClickListener) this);
		ListenerUtil.addClickListenerToCheckBox(chbMoreThanXFamilyEnable,
				(ClickListener) this);
		ListenerUtil.addClickListenerToCheckBox(chbProductId,
				(ClickListener) this);
		ListenerUtil.addClickListenerToCheckBox(chbPaymentModeEnable,
				(ClickListener) this);
		ListenerUtil.addClickListenerToCheckBox(chbFamilyCode,
				(ClickListener) this);
		ListenerUtil.addClickListenerToCheckBox(chbDeliveryModePriceRange,
				(ClickListener) this);
	}

	private void getContentValuesFromTextFields(ConditionItem item) {

		item.setProductIdValue(CreateElementOnGui
				.getValueTextField(tfProductId));

		item.setNbOfItemsPerOrder(CreateElementOnGui
				.getValueTextField(tfMarketingActionCode));
		item.setLineAmount(CreateElementOnGui
				.getValueTextField(tfLineAmountCond));
		item.setOrderAmount(CreateElementOnGui
				.getValueTextField(tfOrderAmountCond));
		item.setNetAmount(CreateElementOnGui.getValueTextField(tfNetAmountCond));
		item.setSalesIdValue(CreateElementOnGui.getValueTextField(tfSalesId));
		item.setProductCodeValue(CreateElementOnGui
				.getValueTextField(tfProductCode));

		item.setPromotionValue(CreateElementOnGui
				.getValueTextField(tfPromotionItemCode));
		item.setMoreThanXOfFamilyValue(CreateElementOnGui
				.getValueTextField(tfMoreThanXFamilyValue));
		item.setRuleName(CreateElementOnGui.getValueTextField(tfRuleName));
		item.setDeliveryModePriceRangeValue(CreateElementOnGui
				.getValueTextField(tfDeliveryModePriceRange));
		item.setNbOfItemsPerOrder(CreateElementOnGui
				.getValueTextField(tfNbOfItemPerOrderCond));
	}

	private void getContentValuesFromTextAreas(ConditionItem item) {
		item.setDescription(CreateElementOnGui.getValueTextArea(taDescription));
	}

	private void getContentValuesFromDropdownBoxes(ConditionItem item) {
		item.setBusLine(CreateElementOnGui.getValueComboBox(cbbBusLine));
		item.setCountry(CreateElementOnGui.getValueSelect(cbbCountry));
		item.setCurrencyValue(CreateElementOnGui.getValueSelect(cbbCurrency));
		item.setLanguageValue(CreateElementOnGui.getValueSelect(cbbLanguage));
		item.setChannelValue(CreateElementOnGui.getValueSelect(cbbChannel));
		item.setPaymentModeValue(CreateElementOnGui
				.getValueSelect(cbbPaymentMode));
		item.setShippingModeValue(CreateElementOnGui
				.getValueSelect(cbbShippingMode));
		item.setFamilyValue(CreateElementOnGui.getValueSelect(cbbFamilyCode));
		item.setSubFamilyValue(CreateElementOnGui
				.getValueSelect(cbbSubFamilyCode));
		item.setCategoryValue(CreateElementOnGui.getValueSelect(cbbCategory));
		item.setCustommerVip(getFieldValue(cbbCustomerVip));
		item.setPriceType(PriceType.parse(getFieldValue(cbbPriceType)));

		item.setPromotionActive(Boolean.TRUE);
	}

	private String getFieldValue(Field field) {
		String value = "";
		if (null != field.getValue()) {
			value = field.getValue().toString();
		}
		return value;
	}

	public ConditionItem getContentValues() {
		ConditionItem item = new ConditionItem();
		// Extra field
		item.setDomainRuleId(this.promotionId);
		String ruleId = null;
		if (tfRuleName.getValue() == null) {
			item.setRuleId("");
		} else {
			ruleId = ((String) tfRuleName.getValue()).trim().replace(" ", "_");
			item.setRuleId(ruleId);
		}

		if (ruleId == null) {
			item.setDescriptionId("");
		} else {
			item.setDescriptionId(ruleId + "-DescID");
		}

		if (this.environment == null) {
			item.setEnvironment(DefaultObjectFactory.newDefaultEnvironment());
			item.setBeginDate(new Date());
			item.setEndDate(null);
		} else {
			item.setEnvironment(this.environment);
			item.setBeginDate((Date) this.tfBeginDate.getValue());
			item.setEndDate((Date) this.tfEndDate.getValue());
		}

		if (this.tfSalience.getValue() != null) {
			try {
				Object lience = this.tfSalience.getValue();
				if (lience instanceof Integer) {
					item.setSalience((Integer) lience);
				} else if (lience instanceof String) {
					Integer salience = Integer.parseInt((String) lience);
					item.setSalience(salience);
				} else {
					item.setSalience(0);
				}
			} catch (NumberFormatException | ClassCastException ex) {
				item.setSalience(0);
			}
		} else {
			item.setSalience(0);
		}

		getContentValuesFromCheckBoxs(item);
		getContentValuesFromTextFields(item);
		getContentValuesFromTextAreas(item);
		getContentValuesFromDropdownBoxes(item);
		getContentValueWithAfm(item);
		if (cbbCityCode.getValue() != null) {
			item.setCityTypeValue(cbbCityCode.getValue().toString());
		}

		return item;
	}

	private void getContentValuesFromCheckBoxs(ConditionItem item) {
		item.setCurrencyEnable(CreateElementOnGui
				.getEnableFromSelect(cbbCurrency));
		item.setLanguageEnable(CreateElementOnGui
				.getEnableFromSelect(cbbLanguage));
		item.setBundleDefinitionEnable(CreateElementOnGui
				.getValueCheckBox(chbBundleDefinition));
		item.setProductIdEnable(CreateElementOnGui
				.getValueCheckBox(chbProductId));
		item.setOneProductForEachSubFamilyEnable(CreateElementOnGui
				.getValueCheckBox(chbOneProduceForEachSubFamily));
		item.setOfferIdEnable(CreateElementOnGui.getValueCheckBox(chbOfferId));
		item.setBrandEnable(CreateElementOnGui.getValueCheckBox(chbBrand));
		item.setLotsEnable(CreateElementOnGui.getValueCheckBox(chbLots));
		item.setProductCodeEnable(CreateElementOnGui
				.getValueCheckBox(chbProductCode));
		item.setSubFamilyEnable(CreateElementOnGui
				.getValueCheckBox(chbSubFamilly));
		item.setCategoryEnable(CreateElementOnGui.getValueCheckBox(chbCategory));
		item.setMoreThanXOfFamilyEnable(CreateElementOnGui
				.getValueCheckBox(chbMoreThanXFamilyEnable));
		item.setCityTypeEnable(CreateElementOnGui.getValueCheckBox(chbCityType));
		item.setSalesIdEnable(CreateElementOnGui.getValueCheckBox(chbSalesId));
		item.setPromotionCodeEnable(CreateElementOnGui
				.getValueCheckBox(chbPromotionCode));
		item.setFamilyEnable(CreateElementOnGui.getValueCheckBox(chbFamilyCode));
		item.setCategoryEnable(CreateElementOnGui.getValueCheckBox(chbCategory));
		item.setShippingModeEnable(CreateElementOnGui
				.getValueCheckBox(chbShippingMode));
		item.setPaymentModeEnable(CreateElementOnGui
				.getValueCheckBox(chbPaymentModeEnable));
		item.setChannelEnable(CreateElementOnGui
				.getValueCheckBox(chbChannelEnable));
		item.setDeliveryModePriceRangeEnable(CreateElementOnGui
				.getValueCheckBox(chbDeliveryModePriceRange));
	}

	private void setFieldEnabled() {
		setFieldEnableOfPromotionConnected();
		setFieldEnableOrdersConditions();
		setFieldEnableApplies();
		
	}

	private void setFieldEnableOrdersConditions() {
		CreateElementOnGui.setTextFieldEnable(chbMoreThanXFamilyEnable,
				tfMoreThanXFamilyValue);
	}

	/**
	 * Function set enable for region PromotionConnected
	 */
	private void setFieldEnableOfPromotionConnected() {
		CreateElementOnGui.setSelectBoxEnable(chbChannelEnable, cbbChannel);
		CreateElementOnGui.setSelectBoxEnable(chbPaymentModeEnable,
				cbbPaymentMode);
		CreateElementOnGui.setSelectBoxEnable(chbShippingMode, cbbShippingMode);
		CreateElementOnGui.setTextFieldEnable(chbPromotionCode,
				tfPromotionItemCode);
		CreateElementOnGui.setTextFieldEnable(chbSalesId, tfSalesId);
		//sac need to fix
		//CreateElementOnGui.setTextFieldEnable(chbCityType, cbbCityCode);
		// CreateElementOnGui.setSelectBoxEnable(chbCityType, cbbCityCode);
	}

	/**
	 * Function set enable for region Applies
	 */
	private void setFieldEnableApplies() {
		CreateElementOnGui.setSelectBoxEnable(chbFamilyCode, cbbFamilyCode);
		CreateElementOnGui.setSelectBoxEnable(chbSubFamilly, cbbSubFamilyCode);
		CreateElementOnGui.setSelectBoxEnable(chbCategory, cbbCategory);
		CreateElementOnGui.setTextFieldEnable(chbProductCode, tfProductCode);
		CreateElementOnGui.setTextFieldEnable(chbProductId, tfProductId);
		CreateElementOnGui.setTextFieldEnable(chbLots, tfLots);
		CreateElementOnGui.setTextFieldEnable(chbBrand, tfBrand);
		CreateElementOnGui.setTextFieldEnable(chbOfferId, tfOfferId);
		CreateElementOnGui.setTextFieldEnable(chbBundleDefinition,
				tfBundleDefinition);
		CreateElementOnGui.setTextFieldEnable(chbOneProduceForEachSubFamily,
				tfOneProduceForEachSubFamily);
		CreateElementOnGui.setTextFieldEnable(chbDeliveryModePriceRange,
				tfDeliveryModePriceRange);
	}

	private void setContentValuesForCheckBoxes(ConditionItem item) {
		chbBundleDefinition.setValue(BooleanUtil.getValueWithoutNull(item
				.getBundleDefinitionEnable()));

		chbProductId.setValue(BooleanUtil.getValueWithoutNull(item
				.getProductIdEnable()));

		chbOneProduceForEachSubFamily
				.setValue(BooleanUtil.getValueWithoutNull(item
						.getOneProductForEachSubFamilyEnable()));

		chbOfferId.setValue(BooleanUtil.getValueWithoutNull(item
				.getOfferIdEnable()));

		chbBrand.setValue(BooleanUtil.getValueWithoutNull(item.getBrandEnable()));

		chbLots.setValue(BooleanUtil.getValueWithoutNull(item.getLotsEnable()));

		chbProductCode.setValue(BooleanUtil.getValueWithoutNull(item
				.getProductCodeEnable()));

		chbCategory.setValue(BooleanUtil.getValueWithoutNull(item
				.getCategoryEnable()));

		chbMoreThanXFamilyEnable.setValue(BooleanUtil.getValueWithoutNull(item
				.getMoreThanXOfFamilyEnable()));

		chbCityType.setValue(BooleanUtil.getValueWithoutNull(item
				.getCityTypeEnable()));

		chbSalesId.setValue(BooleanUtil.getValueWithoutNull(item
				.getSalesIdEnable()));

		chbShippingMode.setValue(BooleanUtil.getValueWithoutNull(item
				.getShippingModeEnable()));

		chbPromotionCode.setValue(BooleanUtil.getValueWithoutNull(item
				.getPromotionCodeEnable()));

		chbFamilyCode.setValue(BooleanUtil.getValueWithoutNull(item
				.getFamilyEnable()));

		chbSubFamilly.setValue(BooleanUtil.getValueWithoutNull(item
				.getSubFamilyEnable()));

		chbChannelEnable.setValue(BooleanUtil.getValueWithoutNull(item
				.getChannelEnable()));

		chbPaymentModeEnable.setValue(BooleanUtil.getValueWithoutNull(item
				.getPaymentModeEnable()));

		chbDeliveryModePriceRange.setValue(BooleanUtil.getValueWithoutNull(item
				.getDeliveryModePriceRangeEnable()));
		// cbbPriceType.setValue(PriceType.parse(item.getPriceType()));
		if (null != item.getPriceType()) {
			cbbPriceType.setValue(item.getPriceType());
		}
	}

	private void setContentValuesForPopupDateFields(ConditionItem item) {
		// All PopupDateFields
		tfBeginDate.setValue(DateTimeUtil.getValueWithoutNull(item
				.getBeginDate()));

		tfEndDate.setValue(item.getEndDate());
	}

	private void setContentValuesForDropdownBoxes(ConditionItem item) {
		// All ComboBoxs
		cbbBusLine.setValue(item.getBusLine());
		if (StringUtil.isEmptyOrBlank((String) cbbBusLine.getValue())) {
			cbbBusLine.setValue(cbbBusLine.getItemIds().iterator().next());
		}
//		reloadAllSelectBox(cbbBusLine.getValue().toString());
		cbbBusLine.setEnabled(!isUpdate);

		CreateElementOnGui.setSelectBoxValue(cbbCountry, StringUtil
				.getValueWithoutNull(item.getCountry()).toUpperCase());
		CreateElementOnGui.setSelectBoxValue(cbbLanguage,
				item.getLanguageValue());
		CreateElementOnGui
				.setSelectBoxValue(cbbChannel, item.getChannelValue());
		CreateElementOnGui.setSelectBoxValue(cbbPaymentMode,
				item.getPaymentModeValue());
		CreateElementOnGui.setSelectBoxValue(cbbCurrency,
				item.getCurrencyValue());
		CreateElementOnGui.setSelectBoxValue(cbbFamilyCode,
				item.getFamilyValue());
		CreateElementOnGui.setSelectBoxValue(cbbShippingMode,
				item.getShippingModeValue());
		CreateElementOnGui.setSelectBoxValue(cbbSubFamilyCode,
				item.getSubFamilyValue());
		CreateElementOnGui.setSelectBoxValue(cbbCategory,
				item.getCategoryValue());
		CreateElementOnGui.setSelectBoxValue(cbbCustomerVip,
				item.getCustommerVip());
		CreateElementOnGui.setSelectBoxValue(cbbPriceType, item.getPriceType());
	}

	private void setContentValuesForTextFields(ConditionItem item) {
		tfOneProduceForEachSubFamily.setValue(item
				.getOneProductForEachSubFamilyValue());
		tfProductId.setValue(item.getProductIdValue());
		tfBundleDefinition.setValue(item.getBundleDefinitionValue());
		tfCategory.setValue(item.getCategoryValue());
		tfMarketingActionCode.setValue(item.getMarketingActionCode());
		tfNbOfItemPerOrderCond.setValue(StringUtil
				.correctIntegerFieldFormat(item.getNbOfItemsPerOrder()));
		tfLineAmountCond.setValue(StringUtil.correctDoubleFieldFormat(item
				.getLineAmount()));
		tfOrderAmountCond.setValue(StringUtil.correctDoubleFieldFormat(item
				.getOrderAmount()));
		tfNetAmountCond.setValue(StringUtil.correctDoubleFieldFormat(item
				.getNetAmount()));

		tfProductCode.setValue(item.getProductCodeValue());
		tfOfferId.setValue(StringUtil.correctIntegerFieldFormat(item
				.getOfferIdValue()));
		tfLots.setValue(StringUtil.correctIntegerFieldFormat(item
				.getLotsValue()));
		tfBrand.setValue(item.getBrandValue());
		tfSalesId.setValue(StringUtil.correctIntegerFieldFormat(item
				.getSalesIdValue()));
		tfPromotionItemCode.setValue(item.getPromotionValue());
		tfSubFamily.setValue(item.getSubFamilyValue());
		tfMoreThanXFamilyValue.setValue(StringUtil
				.correctIntegerFieldFormat(item.getMoreThanXOfFamilyValue()));
		tfDeliveryModePriceRange
				.setValue(item.getDeliveryModePriceRangeValue());
	}

	private void setContentValuesForExtraFields(ConditionItem item,
			boolean isUpdateRequest) {
		// Extra fields
		this.promotionId = item.getDomainRuleId();
		if (item.getEnvironment() == null) {
			this.environment = DefaultObjectFactory.newDefaultEnvironment();
		} else {
			this.environment = item.getEnvironment();
		}
		taDescription.setValue(item.getDescription());
		tfSalience.setValue(item.getSalience());

		oldName = item.getRuleName();
		// ver2
		if (isUpdateRequest) {
			tfRuleName.setValue(item.getRuleName());
		} else {
			String name ="";
			if (item.getRuleName()!= null){
				 name = item.getRuleName()+" "+DateTimeUtil.getFormatNow();
			}
			 
			tfRuleName.setValue(name);
		}

	}

	public void setContentValues(ConditionItem item, boolean isUpdateRequest) {
		isUpdate = isUpdateRequest;
		reload();
		setContentValuesForExtraFields(item, isUpdateRequest);
		setContentValuesForPopupDateFields(item);
		setContentValuesForCheckBoxes(item);
		setContentValuesForDropdownBoxes(item);
		setContentValuesForTextFields(item);

		if (item == null || item.getCityTypeValue() == null) {			
			cbbCityCode.setVisible(Boolean.FALSE);
			chbCityType.setVisible(Boolean.FALSE);
			chbCityType.setValue(Boolean.FALSE);
		} else {
			if (item.getCountry().equals(COUNTRY_CODE)) {
				cbbCityCode.setVisible(Boolean.TRUE);
				//cbbCityCode.setEnabled(Boolean.TRUE);
				cbbCityCode.setValue(item.getCityTypeValue());
				chbCityType.setVisible(Boolean.TRUE);
				chbCityType.setValue(Boolean.TRUE);
			} else {
				cbbCityCode.setVisible(Boolean.FALSE);
				cbbCityCode.setValue(null);
				chbCityType.setVisible(Boolean.FALSE);
				chbCityType.setValue(Boolean.FALSE);
			}
		}

		setFieldEnabled();
	}

	private PromotionConnectedSelectionPopup promotionConnectedSelectionPopup = null;
	private AppliesSelectionPopup appliesSelectionPopup = null;

	@Override
	public void reload() {

	}

	private void reloadAllSelectBox(String roleName) {
		Hashtable<String, List<SystemDetail>> map = BusinessFactory
				.getSystemBusiness().findSystemDetailByRoleAndLangAndSys(
						roleName, SessionData.getLanguage(),
						TableName.COUNTRY.toString(),
						TableName.LANGUAGE.toString(),
						TableName.PAYMENT_MODE.toString(),
						TableName.CHANNEL.toString(),
						TableName.CURRENCY.toString(),
						TableName.FAMILY_CODE.toString(),
						TableName.SUB_FAMILY_CODE.toString(),
						TableName.OFFER_CATEGORIES.toString(),
						TableName.DELIVERY_MODE.toString());
		CreateElementOnGui.reloadSelectBoxItems(cbbCountry, TableName.COUNTRY.toString(), map.get(TableName.COUNTRY.toString()));
		CreateElementOnGui.reloadSelectBoxItems(cbbLanguage, TableName.LANGUAGE.toString(), map.get(TableName.LANGUAGE.toString()));
		CreateElementOnGui.reloadSelectBoxItems(cbbPaymentMode, TableName.PAYMENT_MODE.toString(), map.get(TableName.PAYMENT_MODE.toString()));
		CreateElementOnGui.reloadSelectBoxItems(cbbCurrency, TableName.CURRENCY.toString(), map.get(TableName.CURRENCY.toString()));
		CreateElementOnGui.reloadSelectBoxItems(cbbFamilyCode, TableName.FAMILY_CODE.toString(), map.get(TableName.FAMILY_CODE.toString()));
		CreateElementOnGui.reloadSelectBoxItems(cbbSubFamilyCode, TableName.SUB_FAMILY_CODE.toString(), map.get(TableName.SUB_FAMILY_CODE.toString()));
		CreateElementOnGui.reloadSelectBoxItems(cbbCategory, TableName.OFFER_CATEGORIES.toString(), map.get(TableName.OFFER_CATEGORIES.toString()));
		CreateElementOnGui.reloadSelectBoxItems(cbbShippingMode, TableName.DELIVERY_MODE.toString(), map.get(TableName.DELIVERY_MODE.toString()));
		CreateElementOnGui.reloadSelectBoxItems(cbbChannel, TableName.CHANNEL.toString(), map.get(TableName.CHANNEL.toString()));
	}

	@Override
	public void valueChange(ValueChangeEvent event) {
		Property property = event.getProperty();
		String value = null;
		if (property != null) {
			value = replace((String) property.getValue());
			property.setValue(value);
		}
	}

	private List<DomainRule> checkExistPromotionCode(String promotionCode) {
		List<DomainRule> existRules = new ArrayList<>();
		String[] inputPromotionCode = promotionCode.split(";");
		final IController domainController = ControllerFactory
				.getDomainRuleController();
		List<BeanItem> items = domainController.getPaginationList(1,
				Integer.MAX_VALUE);
		if (this.promotionId == null) {			
			for (BeanItem item : items) {
				DomainRule domainRule = (DomainRule) item.getBean();
				String[] spitPromotionCode = domainRule.getPromotionValue()
						.split(";");
				for (String inputCode : inputPromotionCode) {
					for (String domainRuleProCode : spitPromotionCode) {
						if (domainRuleProCode.equals(inputCode)) {
							existRules.add(domainRule);
						}
					}
				}
			}
		} else {			
			for (BeanItem item : items) {
				if (!this.promotionId.equals(((DomainRule) item.getBean())
						.getDomainRuleId())) {
					DomainRule domainRule = (DomainRule) item.getBean();
					if (!StringUtil.isEmptyOrBlank(domainRule.getPromotionValue())) {
						String[] splitDatacodes = domainRule.getPromotionValue()
								.split(";");
						for (String inputCode : inputPromotionCode) {
							for (String code : splitDatacodes) {
								if (code.equals(inputCode)) {
									existRules.add(domainRule);
								}
							}
						}
					}
				}
			}
		}

		return existRules;
	}

	public void savePromotion() {
		boolean success = validate();
		if (success) {
			if (parentView.isValidated()) {
				Boolean saved = Boolean.FALSE;
				DomainRule domainRule = parentView.getCurrentDomainRule();
				String ruleName = domainRule.getRuleName();
				saved = BusinessFactory.getRuleBusiness().saveRule(domainRule, SessionData.getRoleName());
				if (saved) {
					isUpdate = Boolean.FALSE;
					getWindow().showNotification(
							ruleName,
							SessionData.getI18N().getMessage(
									Constants.SUCCESSFULLY_MESSAGE),
							Notification.TYPE_WARNING_MESSAGE);
					parentView.showPromotionListView(Boolean.FALSE, Boolean.TRUE);
				} else {
					getWindow().showNotification(
							SessionData.getI18N().getMessage(
									Constants.FAILED_MESSAGE),
							Notification.TYPE_WARNING_MESSAGE);
				}

			} else {
				getWindow()
						.showNotification(
								SessionData
										.getI18N()
										.getMessage(
												Constants.NOTIFY_CONSTRAINT_ERROR_AT_ADVANTAGE_VIEW),
								Notification.TYPE_WARNING_MESSAGE);
			}
		}
	}

	@Override
	public void buttonClick(ClickEvent event) {
		final Button source = event.getButton();
		if (source.equals(btnSave)) {
			LOG.info(DateTimeUtil.getNow() + "Click save button");
			String inputCode = (String) tfPromotionItemCode.getValue();
			if (!inputCode.isEmpty()) {
				List<DomainRule> existPromotion = checkExistPromotionCode(inputCode);
				if (existPromotion.size() > 0) {
					if (promotionCodePopup == null) {
						// Disable main view when using popup "select"
						if (this.getApplication().getContext() instanceof MainView) {
							((MainView) this.getApplication().getContext())
									.setEnabled(false);
						}
						final Window w = new Window();
						getApplication().getMainWindow().addWindow(w);
						w.setCaption(SessionData.getI18N().getMessage(
								Constants.EXIST_PROMOTION_CODE));
						promotionCodePopup = new PromotionCodePopup(this,
								existPromotion);
						promotionCodePopup.setSizeFull();
						promotionCodePopup.setCaption(SessionData.getI18N()
								.getMessage(Constants.EXIST_PROMOTION_CODE));

						w.addListener(new Window.CloseListener() {
							private static final long serialVersionUID = 1L;

							@Override
							public void windowClose(CloseEvent e) {
								if (e.getSource() == w) {
									promotionCodePopup = null;
								}
							}
						});

						w.setContent(promotionCodePopup);
						w.setWidth(450, Window.UNITS_PIXELS);
						w.setHeight(400, Window.UNITS_PIXELS);
					}
				} else {
					savePromotion();
				}
			} else {
				savePromotion();
			}

		} else if (source.equals(btnCancel)) {
			LOG.info(DateTimeUtil.getNow() + "Click cancel button");
			isUpdate = false;
			removeError();
			parentView.showPromotionListView(Boolean.FALSE, Boolean.TRUE);
		} else if (source.equals(btnSelectApplies)) {
			LOG.info(DateTimeUtil.getNow()
					+ "Click select button. Show popup to fill in detail infomation");

			if (appliesSelectionPopup == null) {
				// Disable main view when using popup "select"
				if (this.getApplication().getContext() instanceof MainView) {
					((MainView) this.getApplication().getContext())
							.setEnabled(false);
				}
				// Show "select" popup
				final Window wind = new Window();
				getApplication().getMainWindow().addWindow(wind);
				AppliesSelection appliesSelection = getAppliesSelectionSearchItem();

				appliesSelectionPopup = new AppliesSelectionPopup(
						appliesSelection);
				appliesSelectionPopup.setSizeFull();
				appliesSelectionPopup.setCaption(SessionData.getI18N()
						.getMessage(Constants.APPLIES_SELECTION_POPUP));

				wind.addListener(new Window.CloseListener() {
					private static final long serialVersionUID = 1L;

					// Close-listener
					public void windowClose(CloseEvent e) {
						if (e.getSource() == wind) {
							AppliesSelection p = appliesSelectionPopup
									.getAppliesSelection();
							setValueDefaultEnabledChecboxAndTextField(
									p.getProductCode(), chbProductCode,
									tfProductCode);
							setValueDefaultEnabledChecboxAndTextField(
									p.getProductId(), chbProductId, tfProductId);
							setValueDefaultEnabledChecboxAndTextField(
									p.getBrand(), chbBrand, tfBrand);
							setValueDefaultEnabledChecboxAndTextField(
									p.getLotId(), chbLots, tfLots);
							setValueDefaultEnabledChecboxAndTextField(
									p.getOfferId(), chbOfferId, tfOfferId);

							if (p.getCountryCode() == null) {
								cbbCountry.setValue("");
							} else {
								if (StringUtil.isEmptyOrBlank(p
										.getCountryCode())) {
									cbbCountry.setValue(p.getCountryCode());
								} else {
									cbbCountry.setValue("");
								}
							}

							setValueDefaultEnabledForSubFamily(
									p.getSubFamily(), chbSubFamilly,
									cbbSubFamilyCode);
							setValueDefaultEnabledChecboxAndSelectBox(
									p.getCategory(), chbCategory, cbbCategory);
							setValueDefaultEnabledChecboxAndSelectBox(
									p.getFamily(), chbFamilyCode, cbbFamilyCode);
							appliesSelectionPopup = null;
						}
					}
				});
				wind.setContent(appliesSelectionPopup);
				wind.setWidth(800, Window.UNITS_PIXELS);
				wind.setHeight(660, Window.UNITS_PIXELS);
				wind.center();
			}

		} else if (source.equals(btnSelectPromotionConnected)) {
			LOG.info(DateTimeUtil.getNow()
					+ "Click select button. Show popup to fill in detail infomation");

			if (promotionConnectedSelectionPopup == null) {
				// Disable main view when using popup "select"
				if (this.getApplication().getContext() instanceof MainView) {
					((MainView) this.getApplication().getContext())
							.setEnabled(false);
				}
				// Show "select" popup
				final Window w = new Window();
				getApplication().getMainWindow().addWindow(w);
				PromotionConnectedSelection promotionConnectedSelection = getPromotionConnectedSelectionSearchItem();

				promotionConnectedSelectionPopup = new PromotionConnectedSelectionPopup(
						promotionConnectedSelection);
				promotionConnectedSelectionPopup.setSizeFull();
				promotionConnectedSelectionPopup.setCaption(SessionData
						.getI18N().getMessage(
								Constants.PROMOTION_CONNECTED_SELECTION_POPUP));

				w.addListener(new Window.CloseListener() {
					private static final long serialVersionUID = 1L;

					// Close-listener
					public void windowClose(CloseEvent e) {

						if (e.getSource() == w) {
							PromotionConnectedSelection promotion = promotionConnectedSelectionPopup
									.getPromotionConnectedSelection();
							setPopupPromotionConnected(promotion);
						}
					}
				});
				w.setContent(promotionConnectedSelectionPopup);
				w.setWidth(800, Window.UNITS_PIXELS);
				w.setHeight(660, Window.UNITS_PIXELS);
				w.center();
			}
		} else if (source.equals(chbChannelEnable)) {
			CreateElementOnGui
					.setSelectBoxEnable((CheckBox) source, cbbChannel);

		} else if (source.equals(chbBundleDefinition)) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source,
					tfBundleDefinition);

		} else if (source.equals(chbProductId)) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source,
					tfProductId);

		} else if (source.equals(chbOneProduceForEachSubFamily)) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source,
					tfOneProduceForEachSubFamily);

		} else if (source.equals(chbOfferId)) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source, tfOfferId);

		} else if (source.equals(chbLots)) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source, tfLots);

		} else if (source.equals(chbBrand)) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source, tfBrand);

		} else if (source.equals(chbProductCode)) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source,
					tfProductCode);

		} else if (source.equals(chbSubFamilly)) {
			CreateElementOnGui.setSelectBoxEnable((CheckBox) source,
					cbbSubFamilyCode);

		} else if (source.equals(chbCategory)) {
			CreateElementOnGui.setSelectBoxEnable((CheckBox) source,
					cbbCategory);

		} else if (source.equals(chbMoreThanXFamilyEnable)) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source,
					tfMoreThanXFamilyValue);
			// setChbXofFamilyCheck(enabled);

		} else if (source.equals(chbCityType)) {			
			CreateElementOnGui
					.setComboBoxEnable((CheckBox) source, cbbCityCode);

		} else if (source.equals(chbSalesId)) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source, tfSalesId);

		} else if (source.equals(chbShippingMode)) {
			CreateElementOnGui.setSelectBoxEnable((CheckBox) source,
					cbbShippingMode);

		} else if (source.equals(chbPaymentModeEnable)) {
			CreateElementOnGui.setSelectBoxEnable((CheckBox) source,
					cbbPaymentMode);

		} else if (source.equals(chbPromotionCode)) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source,
					tfPromotionItemCode);
			// setchbPromotionCodeIsCheck(enabled);

		} else if (source.equals(chbFamilyCode)) {
			// setchbPromotionCodeIsCheck(enabled);
			CreateElementOnGui.setSelectBoxEnable((CheckBox) source,
					cbbFamilyCode);

		} else if (source.equals(chbDeliveryModePriceRange)) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source,
					tfDeliveryModePriceRange);

		}
	}

	private AppliesSelection getAppliesSelectionSearchItem() {
		AppliesSelection as = new AppliesSelection();
		as.setProductCode((String) tfProductCode.getValue());
		as.setProductId((String) tfProductId.getValue());
		as.setCountryCode((String) cbbCountry.getValue());
		as.setBrand((String) tfBrand.getValue());

		if (cbbFamilyCode.getValue() == null) {
			as.setFamily(null);
		} else {
			as.setFamily((String) cbbFamilyCode.getValue());
		}

		if (cbbBusLine == null) {
			as.setBussinesLine(null);
		} else {
			as.setBussinesLine((String) cbbBusLine.getValue());
		}

		as.setFamily(null);
		as.setLotId((String) tfLots.getValue());
		as.setOfferId((String) tfOfferId.getValue());
		as.setSubFamily((String) tfSubFamily.getValue());
		return as;
	}

	private PromotionConnectedSelection getPromotionConnectedSelectionSearchItem() {
		PromotionConnectedSelection ps = new PromotionConnectedSelection();

		if (cbbChannel.getValue() == null) {
			ps.setChannelValue(null);
		} else {
			ps.setChannelValue((String) cbbChannel.getValue());
		}

		if (cbbCountry.getValue() == null) {
			ps.setCountryCode(null);
		} else {
			ps.setCountryCode((String) cbbCountry.getValue());
		}

		if (cbbBusLine.getValue() == null) {
			ps.setBussinessLine(null);
		} else {
			ps.setBussinessLine((String) cbbBusLine.getValue());
		}
		return ps;
	}

	/**
	 * This is the function create condition view
	 */
	private void buildMainLayout() {
		conditionCustomLayout = new CustomLayout("ConditionSelection");
		// lblEnvironmentName
		lblEnvironmentName = new Label();
		lblEnvironmentName.setImmediate(true);
		lblEnvironmentName.setStyleName("inline");
		conditionCustomLayout.addComponent(lblEnvironmentName, "lblEnv");

		buidRuleAttributeRegion();
		buidGeneralConditionRegion();
		buildCustomerConditionsRegion();
		buildAccessManagementRegion();
		buildPromotionConnectedRegion();
		buildOrdersConditionsRegion();
		buildGeneralAppliesTo();
		buildControlCustomLayout();
	}

	private Label lblCustomerConditions;
	private ListSelect lbxServiceProviderDomainId;
	private Select cbbCustomerRole;
	private Select cbbCustomerStatus;
	private Select cbbCustomerClassification;
	private Select cbbCustomerBalanceOperator;
	private TextField tfCustomerBalance;
	
	private void buildCustomerConditionsRegion() {
		lblCustomerConditions = CreateElementOnGui.createLabelPosition("inline",
				conditionCustomLayout, "lcLblCustomerConditions", null);
		lbxServiceProviderDomainId = CreateElementOnGui.createListSelectPosition(StyleNameCss.INLINE_FILED.getStyleName(), conditionCustomLayout, "lcCbbCustomerRole");
		cbbCustomerRole = CreateElementOnGui.createComboBoxPosition(StyleNameCss.INLINE_FILED.getStyleName(), conditionCustomLayout, "lcCbbCustomerRole");
		cbbCustomerStatus = CreateElementOnGui.createComboBoxPosition(StyleNameCss.INLINE_FILED.getStyleName(), conditionCustomLayout, "lcCbbCustomerStatus");
		cbbCustomerClassification = CreateElementOnGui.createComboBoxPosition(StyleNameCss.INLINE_FILED.getStyleName(), conditionCustomLayout, "lcCbbCustomerClassification");
		cbbCustomerBalanceOperator = CreateElementOnGui.createComboBoxPosition(StyleNameCss.INLINE_FILED.getStyleName(), conditionCustomLayout, "lcCbbCustomerBalanceOperator");
		tfCustomerBalance = CreateElementOnGui.createTexboxPosition(StyleNameCss.INLINE_FILED.getStyleName(), conditionCustomLayout, "lcTfCustomerBalance");
	}
	
	private void buildAccessManagementRegion() {
		lblAccessManagement = CreateElementOnGui.createLabelPosition("inline",
				conditionCustomLayout, "lcLblAccessManagement", null);
		cbbLocation = CreateElementOnGui.createComboBoxPosition(StyleNameCss.INLINE_FILED.getStyleName(), conditionCustomLayout, "lcCbbLocation");
		cbbAccessType = CreateElementOnGui.createComboBoxPosition(StyleNameCss.INLINE_FILED.getStyleName(), conditionCustomLayout, "lcCbbAccessType");
		tfAccessDatetime = CreateElementOnGui.createPopupDateFieldPosition(StyleNameCss.INLINE_FILED.getStyleName(), conditionCustomLayout, "lcTfAccessDatetime");
		tfAccessProductId = CreateElementOnGui.createTexboxPosition(StyleNameCss.INLINE_FILED.getStyleName(), conditionCustomLayout, "lcTfAccessProductId");
	}

	/**
	 * This is function build region RuleAttributes of condition view.
	 */

	private void buidRuleAttributeRegion() {
		lblRuleAttributes = CreateElementOnGui.createLabelPosition("inline",
				conditionCustomLayout, "lblRuleAttributes", null);

		tfRuleName = CreateElementOnGui.createTexboxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "lcRuleName");

		taDescription = CreateElementOnGui.createTextAreaPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "lcDescription");

		tfSalience = CreateElementOnGui.createIntegerField(
				conditionCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(), "lcPriority");

		cbbCustomerVip = new ComboBox();
		cbbCustomerVip.addItem(CustomerVip.VIP.value());
		cbbCustomerVip.setImmediate(true);
		cbbCustomerVip.setStyleName(StyleNameCss.INLINE_FILED.getStyleName());
		conditionCustomLayout.addComponent(cbbCustomerVip, "lcCustomerVip");

		cbbPriceType = new ComboBox();
		cbbPriceType.setImmediate(true);
		for (PriceType item : PriceType.values()) {
			cbbPriceType.addItem(item);
		}
		cbbPriceType.setItemCaption(PriceType.SELLING_PRICE, SessionData
				.getI18N().getMessage(Constants.SELLING_PRICE));
		cbbPriceType.setItemCaption(PriceType.REAL_PRICE, SessionData.getI18N()
				.getMessage(Constants.REAL_PRICE));
		cbbPriceType.setImmediate(true);
		cbbPriceType.setStyleName(StyleNameCss.INLINE_FILED.getStyleName());
		conditionCustomLayout.addComponent(cbbPriceType, "lcPriceType");
	}

	/**
	 * This is function create region general conditions of condition view
	 */
	private void buidGeneralConditionRegion() {
		lblGeneralConditions = CreateElementOnGui.createLabelPosition(
				StyleNameCss.INLINE.getStyleName(), conditionCustomLayout,
				"lblGeneralConditions", null);
		lblBusiness = CreateElementOnGui.createLabelPosition(
				StyleNameCss.INLINE.getStyleName(), conditionCustomLayout,
				null, null);

		// cbbBusLine
		cbbBusLine = new ComboBox();
		cbbBusLine.setImmediate(false);
		cbbBusLine.setStyleName(StyleNameCss.INLINE_FILED.getStyleName());
		conditionCustomLayout.addComponent(cbbBusLine, "lcCbbBusLine");

		// tfCountry
		cbbCountry = CreateElementOnGui.createComboBoxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "lcCountry");

		// tfBeginDate
		tfBeginDate = CreateElementOnGui.createPopupDateFieldPosition(StyleNameCss.INLINE_FILED.getStyleName(), conditionCustomLayout, "lcBegDate");
		// tfEndDate
		tfEndDate = CreateElementOnGui.createPopupDateFieldPosition(StyleNameCss.INLINE_FILED.getStyleName(), conditionCustomLayout, "lcEndDate");
		// cbbLanguage
		cbbLanguage = CreateElementOnGui.createComboBoxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "lcCbbLanguage");
	}

	/**
	 * This is function create region promotion connected to of condition view
	 */

	private void buildPromotionConnectedRegion() {
		lblPromotionConnectedTo = CreateElementOnGui.createLabelPosition(
				StyleNameCss.INLINE.getStyleName(), conditionCustomLayout,
				"lblPromotionConnected", null);

		chbPromotionCode = CreateElementOnGui.createCheckBox("Promotion code",
				StyleNameCss.INLINE_BOX.getStyleName(), conditionCustomLayout,
				"lcCheckBoxPromotionCode");

		tfPromotionItemCode = CreateElementOnGui.createTexboxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "lcPromotionCode");

		chbChannelEnable = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.SELECT_BOX.getStyleName(), conditionCustomLayout,
				"chbChannelEnable");
		cbbChannel = CreateElementOnGui.createComboBoxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "lcCbbChannel");

		chbPaymentModeEnable = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.SELECT_BOX.getStyleName(), conditionCustomLayout,
				"chbPaymentModeEnable");
		cbbPaymentMode = CreateElementOnGui.createComboBoxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "lcCbbPaymentMode");

		chbShippingMode = CreateElementOnGui.createCheckBox("Shippingmode",
				StyleNameCss.SELECT_BOX.getStyleName(), conditionCustomLayout,
				"lcCheckBoxShippingMode");
		cbbShippingMode = CreateElementOnGui.createComboBoxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "lcShippingMode");

		chbSalesId = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.INLINE_BOX.getStyleName(), conditionCustomLayout,
				"chbSalesId");
		tfSalesId = CreateElementOnGui
				.createIntegerField(conditionCustomLayout,
						StyleNameCss.INLINE_BOX_CCD_REQUIRE.getStyleName(),
						"tfSalesId");

		chbCityType = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.SELECT_BOX.getStyleName(), conditionCustomLayout,
				"lcCheckBoxCity");
		cbbCityCode = new ComboBox();
		cbbCityCode.addItem("1");
		cbbCityCode.addItem("2");
		cbbCityCode.addItem("3");
		cbbCityCode.addItem("4");
		cbbCityCode.addItem("5");
		cbbCityCode.setVisible(Boolean.FALSE);

		cbbCityCode.setStyleName(StyleNameCss.INLINE_FILED.getStyleName());
		conditionCustomLayout.addComponent(cbbCityCode, "cbbCity");

		cbbDeliveryMode = CreateElementOnGui.createComboBoxPosition(
				StyleNameCss.INLINE_FILED_CCD_REQUIRE.getStyleName(),
				conditionCustomLayout, null);

		cbbOffer = CreateElementOnGui.createComboBoxPosition(
				StyleNameCss.INLINE_FILED_CCD_REQUIRE.getStyleName(),
				conditionCustomLayout, null);

		cbbCurrency = CreateElementOnGui.createComboBoxPosition(
				StyleNameCss.INLINE_FILED_CCD_REQUIRE.getStyleName(),
				conditionCustomLayout, "lcCbbCurrency");

		tfMarketingActionCode = CreateElementOnGui.createTexboxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "tfMarketingActionCode");
		// btnSelectPromotionConnected
		btnSelectPromotionConnected = CreateElementOnGui
				.createNativeButtonPosition(
						StyleNameCss.SMALL_BUTTON.getStyleName(),
						conditionCustomLayout, "lcBtnSelectPromotionConnected",
						"");
	}

	/**
	 * This is the function create region order condition of condition view.
	 */
	private void buildOrdersConditionsRegion() {
		lblOrdersConditions = CreateElementOnGui.createLabelPosition(
				StyleNameCss.INLINE.getStyleName(), conditionCustomLayout,
				"lblOrdersConditions", null);
		tfOrderAmountCond = CreateElementOnGui.createDoubleField(
				conditionCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(), "lcOrderAmount");
		tfLineAmountCond = CreateElementOnGui.createDoubleField(
				conditionCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(), "tfLineAmountCond");
		tfNetAmountCond = CreateElementOnGui.createDoubleField(
				conditionCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(), "lcNetAmount");
		tfNbOfItemPerOrderCond = CreateElementOnGui.createIntegerField(
				conditionCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(), "lcNbOfItems");
		chbMoreThanXFamilyEnable = CreateElementOnGui.createCheckBox(
				"More than x of family", null, conditionCustomLayout,
				"lcCheckBoxMoreThan");
		tfMoreThanXFamilyValue = CreateElementOnGui.createIntegerField(
				conditionCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(), "lcMoreThan");
		tfLots = CreateElementOnGui.createIntegerField(conditionCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(), "tfLots");
		tfOfferId = CreateElementOnGui.createIntegerField(
				conditionCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(), "tfOfferId");
		tfSalesId = CreateElementOnGui.createIntegerField(
				conditionCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(), "tfSalesId");
	}

	private void buildControlCustomLayout() {
		// btnSave
		btnSave = CreateElementOnGui.createNativeButtonPosition(
				StyleNameCss.BUTTON_STYLE.getStyleName(),
				conditionCustomLayout, "button_save", "Save");
		// btnCancel
		btnCancel = CreateElementOnGui.createNativeButtonPosition(
				StyleNameCss.RIGHT_BUTTON.getStyleName(),
				conditionCustomLayout, "button_cancel", "Cancel");
		btnCancel.addStyleName("cancel");

		conditionCustomLayout.addComponent(new Label(SessionData.getI18N()
				.getMessage(Constants.CANCEL_BUTTON)), "tipCancel");
	}

	private void buildGeneralAppliesTo() {
		lblAppliesTo = CreateElementOnGui.createLabelPosition(
				StyleNameCss.INLINE.getStyleName(), conditionCustomLayout,
				"lblAppliesTo", null);

		chbFamilyCode = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.SELECT_BOX.getStyleName(), conditionCustomLayout,
				"chbFamilyCode");
		cbbFamilyCode = CreateElementOnGui.createComboBoxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "cbbFamilyCode");

		chbSubFamilly = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.SELECT_BOX.getStyleName(), conditionCustomLayout,
				"chbSubFamilly");
		cbbSubFamilyCode = CreateElementOnGui.createComboBoxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "cbbSubFamilyCode");

		tfSubFamily = CreateElementOnGui.createTexboxPosition(null,
				conditionCustomLayout, null);
		tfSubFamily.setWidth("78px");
		tfSubFamily.setHeight("-1px");

		tfCategory = CreateElementOnGui.createTexboxPosition(null,
				conditionCustomLayout, null);
		tfCategory.setWidth("84px");
		tfCategory.setHeight("-1px");

		chbCategory = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.SELECT_BOX.getStyleName(), conditionCustomLayout,
				"lcCheckBoxCategory");
		cbbCategory = CreateElementOnGui.createComboBoxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "cbbCategory");

		chbProductCode = CreateElementOnGui.createCheckBox("Product code",
				"inline_box", conditionCustomLayout, "lcCheckBoxProductCode");
		tfProductCode = CreateElementOnGui.createTexboxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "lcProductCode");

		chbProductId = CreateElementOnGui.createCheckBox("Product ID",
				StyleNameCss.INLINE_BOX.getStyleName(), conditionCustomLayout,
				"lcCheckBoxProductId");
		tfProductId = CreateElementOnGui.createTexboxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "lcProductId");

		chbLots = CreateElementOnGui.createCheckBox("Lots",
				StyleNameCss.INLINE_BOX.getStyleName(), conditionCustomLayout,
				"chbLots");
		chbLots.setWidth("-1px");
		chbLots.setHeight("-1px");
		tfLots = CreateElementOnGui.createIntegerField(conditionCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(), "tfLots");

		chbBrand = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "chbBrand");
		tfBrand = CreateElementOnGui.createTexboxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "tfBrand");

		chbOfferId = CreateElementOnGui.createCheckBox("Offer ID",
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "chbOfferId");
		chbOfferId.setWidth("-1px");
		chbOfferId.setHeight("-1px");

		tfOfferId = CreateElementOnGui.createIntegerField(
				conditionCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(), "tfOfferId");

		chbBundleDefinition = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, null);
		chbBundleDefinition.setWidth("-1px");
		chbBundleDefinition.setHeight("-1px");

		tfBundleDefinition = CreateElementOnGui.createTexboxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, null);

		chbOneProduceForEachSubFamily = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "chbOneProduceForEachSubFamily");
		chbOneProduceForEachSubFamily.setWidth("-1px");
		chbOneProduceForEachSubFamily.setHeight("-1px");
		
		chbDeliveryModePriceRange = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.INLINE_FILED.getStyleName(), conditionCustomLayout,
				"chbDeliveryModePriceRange");
		chbDeliveryModePriceRange.setWidth("-1px");
		chbDeliveryModePriceRange.setHeight("-1px");


		tfOneProduceForEachSubFamily = CreateElementOnGui.createTexboxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "tfOneProduceForEachSubFamily");

		tfDeliveryModePriceRange = CreateElementOnGui.createTexboxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				conditionCustomLayout, "tfDeliveryModePriceRange");

		
		btnSelectApplies = CreateElementOnGui.createNativeButtonPosition(
				StyleNameCss.SMALL_BUTTON.getStyleName(),
				conditionCustomLayout, "lcBtnSelectApplies", "");
	}

	private void setVisibleToobar(String bussinesLine) {
		if (bussinesLine.equals(Constants.AFM_BUSSINES_LINE)) {
			tfMarketingActionCode.setVisible(false);

			chbLots.setVisible(false);
			tfLots.setVisible(false);

			chbBrand.setVisible(false);
			tfBrand.setVisible(false);

			chbBundleDefinition.setVisible(false);
			tfBundleDefinition.setVisible(false);

			chbOfferId.setVisible(false);
			tfOfferId.setVisible(false);

			chbOneProduceForEachSubFamily.setVisible(false);
			tfOneProduceForEachSubFamily.setVisible(false);
		} else {
			tfMarketingActionCode.setVisible(true);

			chbLots.setVisible(true);
			tfLots.setVisible(true);

			chbBrand.setVisible(true);
			tfBrand.setVisible(true);

			chbBundleDefinition.setVisible(true);
			tfBundleDefinition.setVisible(true);

			chbOfferId.setVisible(true);
			tfOfferId.setVisible(true);

			chbOneProduceForEachSubFamily.setVisible(true);
			tfOneProduceForEachSubFamily.setVisible(true);
		}
	}

	@SuppressWarnings("unused")
	private ListBoxData getBoxDatass(int systemValueRefId) {
		ListBoxData listBoxData = null;
		
		SystemValueRef systemValueRef = BusinessFactory.getSystemBusiness().getSysValRef(systemValueRefId);

		if (systemValueRef == null) {
			listBoxData = null;
		} else {
			listBoxData = new ListBoxData(systemValueRef.getSystemValue()
					.getSystemCode(), systemValueRef.getLabel());
		}
		return listBoxData;
	}

	private void setPopupPromotionConnected(
			PromotionConnectedSelection promotion) {

		if (promotion.getSalesId() == null) {
			chbSalesId.setValue(Boolean.FALSE);
			tfSalesId.setEnabled(Boolean.FALSE);
			tfSalesId.setValue("");

		} else {
			chbSalesId.setValue(Boolean.TRUE);
			tfSalesId.setEnabled(Boolean.TRUE);
			tfSalesId.setValue(promotion.getSalesId());
		}

		cbbCountry.setValue(promotion.getCountryCode());
		promotionConnectedSelectionPopup = null;

		if (promotion.getChannelCode() == null) {
			cbbChannel.setValue(null);
			cbbChannel.setEnabled(false);
			chbChannelEnable.setValue(false);
		} else {
			if (StringUtil.isEmptyOrBlank(promotion.getChannelCode())) {
				cbbChannel.setValue(promotion.getChannelCode());
				cbbChannel.setEnabled(true);
				chbChannelEnable.setValue(true);
			} else {
				cbbChannel.setValue(null);
				cbbChannel.setEnabled(false);
				chbChannelEnable.setValue(false);
			}

		}

	}

	private void setValueDefaultEnabledForSubFamily(String value,
			CheckBox checkBox, Select selectBox) {
		if (StringUtils.isBlank(value)) {
			checkBox.setValue(Boolean.FALSE);
			selectBox.setValue(null);
			selectBox.setEnabled(Boolean.FALSE);
		} else {
			checkBox.setValue(Boolean.TRUE);
			selectBox.setValue(value);
			selectBox.setEnabled(Boolean.TRUE);
		}
	}

	private void setValueDefaultEnabledChecboxAndSelectBox(String value,
			CheckBox checkBox, Select selectBox) {
		if (value == null) {
			checkBox.setValue(Boolean.FALSE);
			selectBox.setValue(null);
			selectBox.setEnabled(Boolean.FALSE);
		} else {
			if (StringUtil.isEmptyOrBlank(value)) {
				checkBox.setValue(Boolean.TRUE);
				selectBox.setValue(value);
				selectBox.setEnabled(Boolean.TRUE);
			} else {
				checkBox.setValue(Boolean.FALSE);
				selectBox.setValue(null);
				selectBox.setEnabled(Boolean.FALSE);
			}
		}
	}

	private void setValueDefaultEnabledChecboxAndTextField(String value,
			CheckBox checkBox, TextField textField) {
		if (value != null && value.length() > 0) {
			checkBox.setValue(true);
			textField.setEnabled(true);
			textField.setValue(value);
		} else {
			checkBox.setValue(false);
			textField.setEnabled(false);
			textField.setValue("");
		}
	}

	private boolean isNullOrEmpty(Object obj) {
		boolean result = true;
		if (null != obj && String.valueOf(obj).trim().length() != 0) {
			result = false;
		}
		return result;
	}

	private void getContentValueWithAfm(ConditionItem item) {
		if (cbbBusLine.getValue().equals(Constants.AFM_BUSSINES_LINE)) {
			item.setMarketingActionCode(null);
			item.setLotsValue(null);
			item.setBrandValue(null);
			item.setOfferIdValue(null);
			item.setBundleDefinitionValue(null);
			item.setOneProductForEachSubFamilyValue(null);
		} else {
			item.setMarketingActionCode(CreateElementOnGui
					.getValueTextField(tfMarketingActionCode));
			item.setLotsValue(CreateElementOnGui.getValueTextField(tfLots));
			item.setBrandValue(CreateElementOnGui.getValueTextField(tfBrand));
			item.setOfferIdValue(CreateElementOnGui
					.getValueTextField(tfOfferId));
			item.setBundleDefinitionValue(CreateElementOnGui
					.getValueTextField(tfBundleDefinition));
			item.setOneProductForEachSubFamilyValue(CreateElementOnGui
					.getValueTextField(tfOneProduceForEachSubFamily));
		}
	}
}
